/**
 * Copyright 2011 Renato de Jesus Manzoni
 * 
 * SED - Software Engineering and Dependability Research Group
 * 
 *     http://www.sed.ic.unicamp.br/
 * 
 * Distributed Systems Laboratory (LSD) in the Institute of Computing (IC) at University of Campinas (UNICAMP)
 * 
 *     http://www.lsd.ic.unicamp.br/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package br.unicamp.ic.lsd.wscaa.concurrent;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.endpoint.ClientCallback;

import br.unicamp.ic.lsd.wscaa.WSCAManager;
import br.unicamp.ic.lsd.wscaa.api.ServiceResponse;

/**
 * @author Renato de Jesus Manzoni <rjmanzoni@gmail.com>
 * 
 */
public class WSCAACallBackResults {

    private WSCAManager manager;

    private List<ServiceResponseCallable> tasks;
    
    private static ExecutorService executor;

    private static Log logger = LogFactory.getLog(WSCAACallBackResults.class);

    public WSCAACallBackResults(final WSCAManager manager) {

	this.manager = manager;

	tasks = new ArrayList<ServiceResponseCallable>();
	
	if(executor == null){
	    executor = Executors.newCachedThreadPool();
	}

    }

    public void addTask(String method, long timeout, ClientCallback cb) {
	tasks.add(new ServiceResponseCallable(method, timeout, cb, manager));
    }

    private List<ServiceResponse> synchronizeAllCallBacks() throws InterruptedException {
	List<ServiceResponse> responses = new ArrayList<ServiceResponse>();
	
	List<Future<ServiceResponse>> futures;

	try {
	    futures = executor.invokeAll(tasks);
	    // sync the results
	    for (Iterator<Future<ServiceResponse>> iterator = futures
		    .iterator(); iterator.hasNext();) {
		Future<ServiceResponse> fut = iterator.next();

		ServiceResponse res = fut.get();

		// just add if res is not null
		if (res != null) {

		    if (logger.isTraceEnabled())
			logger.trace("The first result from "
				+ res.getResponseName()
				+ " is "
				+ (res.hasException() ? res.getException()
					: res.getReponses()[0]));

		    responses.add(res);
		}

	    }

	    return responses;

	} catch (ExecutionException e) {

	    logger.error(e.getLocalizedMessage(), e);
	    
	} 
//	finally {
//	    executor.shutdown();
//	}
	return null;
    }

    public List<ServiceResponse> getResults() throws InterruptedException {
	return synchronizeAllCallBacks();
    }

}
